package copyengine.utils.objectpool
{
	import copyengine.utils.GeneralUtils;
	import copyengine.utils.debug.CELog;
	
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	
	import org.as3commons.reflect.Type;

	public final class CEObjectPoolManger
	{
		private static const GC_INTERVAL_TIME:int = 1000 * 10;

		private static var _instance:CEObjectPoolManger;

		public static function get instance():CEObjectPoolManger
		{
			if (_instance == null)
			{
				_instance = new CEObjectPoolManger();
			}
			return _instance;
		}

		/**
		 *存储所有缓存的可以循环使用的Obj
		 */
		private var objPoolDic:Dictionary;

		private var gcTimer:Timer;

		public function CEObjectPoolManger()
		{
			objPoolDic = new Dictionary();
//			gcTimer = new Timer(GC_INTERVAL_TIME);
//			GeneralUtils.addTargetEventListener(gcTimer, TimerEvent.TIMER, onGcTime);
//			gcTimer.start();
		}

		/**
		 *从对象池中请求出某一个类型的对象
		 *
		 * 注意！！
		 * 			请求出的对象属性值不可靠,需要重新赋值
		 *
		 */
		public function request(_requestObjectClass:Class):*
		{
			var memo:CEObjectPoolMemo = objPoolDic[_requestObjectClass];
			if (memo == null)
			{
				memo = new CEObjectPoolMemo();
				memo.objPool = [];
				objPoolDic[_requestObjectClass] = memo;
			}
			memo.requestValue++;
			if (memo.objPool.length > 0)
			{
				return memo.objPool.pop();
			}
			else
			{
				var newInstance:* = new _requestObjectClass();
				return newInstance;
			}
		}

		public function recycle(_obj:*):void
		{
			//函数有问题 ！！！
			
			
//			if (_obj)
//			{
//				var objType:Type = Type.forInstance(_obj);
//				var memo:CEObjectPoolMemo = objPoolDic[objType.clazz];
//				if (memo)
//				{
//					var isAdd:Boolean = true;
//					for each (var poolObj:* in memo.objPool)
//					{
//						if (poolObj == _obj)
//						{
//							isAdd = false;
//							CELog.log("Recycle the same obj");
//							break;
//						}
//					}
//					if(isAdd)
//					{
//						memo.objPool.push(_obj);
//					}
//				}
//				memo.recyleValue++;
//			}
		}

		private function onGcTime(e:Event):void
		{
			for each (var memo:CEObjectPoolMemo in objPoolDic)
			{
				var value:int = Math.max(memo.requestValue - memo.recyleValue, 0);
				while (memo.objPool.length > value)
				{
					memo.objPool.pop();
				}
				memo.recyleValue = 0;
				memo.requestValue = 0;
			}
		}

	}
}